/**
 * 
 */
package it.battlehorse.scripting.actions;

import it.battlehorse.rcp.sl.annot.Injected;
import it.battlehorse.rcp.sl.annot.Serviceable;
import it.battlehorse.scripting.ScriptSupport;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.script.ScriptException;

import org.apache.commons.logging.Log;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PlatformUI;


/**
 * This action launches an external script. The user is allowed to select the script by filtering 
 * among all the supported languages
 * 
 * @author battlehorse
 *
 */
@Serviceable
public class RunScriptAction implements IWorkbenchWindowActionDelegate {
	
	private Log log ; 
	
	@Injected
	public void setLog(Log log) {
		this.log = log;
	} 
	
	/**
	 * A reference to the last opened file
	 */
	private static String lastOpenedFile = null;

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose()
	 */
	public void dispose() {}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow)
	 */
	public void init(IWorkbenchWindow window) {}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	public void run(IAction action) {
		FileDialog dlg = new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
				SWT.OPEN);
				
		List<String> filterNames = new ArrayList<String>();
		List<String> filterExtensions = new ArrayList<String>();
		ScriptSupport support = new ScriptSupport();
		for (ScriptSupport.Language l : support.getSupportedLanguages()) {
			filterNames.add(l.getName() + " (*." + l.getExtension().get(0) + ")");
			filterExtensions.add("*." +l.getExtension().get(0));			
		}
		filterNames.add("All files (*.*)");
		filterExtensions.add("*.*");
		
		dlg.setFilterNames(filterNames.toArray(new String[filterNames.size()]));
		dlg.setFilterExtensions(filterExtensions.toArray(new String[filterExtensions.size()]));
		if (lastOpenedFile != null) dlg.setFileName(lastOpenedFile);
		
		String f = dlg.open();
		if (f != null) {					
			BufferedReader br = null;
			try {
				lastOpenedFile = f;	
				br = new BufferedReader(new FileReader(f));

				support.runScript(br, getExtension(f),null,true );	
			}
			catch(IOException ioe) {
				log.error("An error occurred while running script " + f + ": " + ioe.getMessage(),ioe);
			}
			catch(ScriptException se) {
				log.error("An error occurred while running script " + f + ": " + se.getMessage(),se);
			}
			finally {
				if (br != null)
					try { br.close(); } catch(Exception ex) {}
			}
		}		

	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {}
	
	private String getExtension(String f) {
		if (f.lastIndexOf('.') != -1) {
			return f.substring(f.lastIndexOf('.')+1);
		}
		else
			return f;
	}

}
